class WebSocketClient {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
  }

  connect(userId) {
    const token = localStorage.getItem('user_info') 
      ? JSON.parse(localStorage.getItem('user_info')).token 
      : ''
    
    this.ws = new WebSocket(`ws://localhost:3000/socket/websocket/${userId}`)
    
    this.ws.onopen = () => {
      console.log('WebSocket连接成功')
      this.reconnectAttempts = 0
      // 发送认证信息
      this.ws.send(JSON.stringify({
        type: 'auth',
        token
      }))
    }

    this.ws.onclose = () => {
      console.log('WebSocket连接关闭')
      this.reconnect(userId)
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
    }
  }

  reconnect(userId) {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      setTimeout(() => {
        this.connect(userId)
      }, 3000)
    }
  }

  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(message))
    }
  }

  close() {
    if (this.ws) {
      this.ws.close()
    }
  }
}

export default new WebSocketClient() 